package pro.ticktock.tools.mbconv;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by lambert on 2017/5/28.
 */
public class Pass3 extends AbstractPass{
  protected Pass3(String origSrcFileName, String srcFileName) throws IOException {
    super(origSrcFileName, srcFileName);
  }

  @Override
  protected void doProcess() throws IOException {
    String line;
    Pattern spaceInDashPattern = Pattern.compile("(\\d)[ ]*-[ ]*(\\d)"); // 065 234 -3
    Pattern badCommaInOP = Pattern.compile("(OP\\.\\d+)(,\\d+)[^.．]");
    Pattern badLInYear = Pattern.compile("l(\\d\\d\\d年)");
    while ((line = srcReader.readLine()) != null) {

      if (line.startsWith(Pass2.CH_TITLE_MARK)) {
        line = line.replaceAll("[ 　]+", "");
      } else {
        line = line.replaceAll("[ ]{2,}", " ");
        line = line.replaceAll("[ 　]{2,}", "　");
      }

      Matcher m = spaceInDashPattern.matcher(line);
      if (m.find()) {
        StringBuffer sb = new StringBuffer();
        int lastEnd = 0;
        do {
          sb.append(line.substring(lastEnd, m.start()));
          sb.append(m.group(1));
          sb.append('-');
          sb.append(m.group(2));
          String s = m.group(0);
          if (s.length() > 3) {
            logWriter.append("Removed spaces: " + s + "\n");
          }
          lastEnd = m.end();
        } while (m.find());
        sb.append(line.substring(lastEnd));
        line = sb.toString();
      }

      m = badCommaInOP.matcher(line);
      if (m.find()) {
        StringBuffer sb = new StringBuffer();
        int lastEnd = 0;
        do {
          sb.append(line.substring(lastEnd, m.start(1)));
          sb.append(m.group(1));
          sb.append('.');
          lastEnd = m.end(1) + 1;
          logWriter.append("Replaced bad comma: " + m.group(1) + m.group(2) + "\n");
        } while (m.find());
        sb.append(line.substring(lastEnd));
        line = sb.toString();
      }

      m = badLInYear.matcher(line);
      if (m.find()) {
        StringBuffer sb = new StringBuffer();
        int lastEnd = 0;
        do {
          sb.append(line.substring(lastEnd, m.start(0)));
          sb.append(1).append(m.group(1));
          lastEnd = m.end(1);
          logWriter.append("Replaced l in year:  " + m.group(0) + "\n");
        } while (m.find());
        sb.append(line.substring(lastEnd));
        line = sb.toString();
      }

      //remove lingering characters .'
      for (int i = 0; i < line.length(); i++) {
        char ch = line.charAt(i);
        if (ch == ' ' || ch == '　') continue;
        else if (ch == '.' || ch == '．' || ch == '\'' || ch == '‘') {
          logWriter.append("Removed lingering at head: " + line + "\n");
          line = line.substring(0, i) + line.substring(i + 1);
          break;
        }
        else break;
      }

      resultWriter.append(line + "\n");
    }
  }
}
